<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="q.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option :label="item.cate_name" :value="item.id" v-for="item in artList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="artIcleList()">筛选</el-button>
            <el-button type="info" size="small" @click="resetAll">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="
            haha = 'file';
            addArtDialog = true;
          "
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artcleList" style="width: 100%" border>
        <el-table-column prop="title" label="文章标题" width="180">
          <template #default={row}>
            <el-link type='success' @click="showArtDetail(row.id)">
              {{row.title}}
            </el-link>            
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="文章分类" width="180">
        </el-table-column>
        <el-table-column prop="pub_date" label="发布时间"> 
          <template #default={row}>
            {{formatDate(row.pub_date)}}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态"> </el-table-column>
        <el-table-column label="操作">
          <template #default={row}>
            <el-button type="danger" size="mini" @click="delArt(row.id)">删除</el-button>
          </template>
        </el-table-column>
        
      </el-table>

      <!-- 发表文章弹框 -->
      <el-dialog
        title="发表文章"
        @close="resetForm"
        :visible.sync="addArtDialog"
        fullscreen
      >
        <el-form
          ref="form"
          :model="artcleForm"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="artcleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select
              v-model="artcleForm.cate_id"
              style="width: 100%"
              placeholder="请选择活动分类"
            >
              <el-option
                :label="item.cate_name"
                :value="item.id"
                v-for="item in artList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="文章内容" prop="content">
            <quill-editor
              v-model="artcleForm.content"
              ref="myQuillEditor"
            ></quill-editor>
          </el-form-item>

          <el-form-item label="文章封面">
            <!-- 用来显示封面的图片 -->
            <img
              src="../../../assets/images/cover.jpg"
              alt=""
              class="cover-img"
              ref="imgRef"
            />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input
              :type="haha"
              style="display: none"
              @change="uplocdImg"
              accept="image/*"
              ref="iptFile"
            />
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="$refs.iptFile.click()"
              >+ 选择封面</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="pubArticle('已发布')"
              >发布</el-button
            >
            <el-button type="info" @click="pubArticle('草稿')"
              >存为草稿</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="q.pagenum"
          :page-sizes="[1, 2, 3, 4]"
          :page-size="q.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

      <!-- 查看文章详情的对话框 -->
      <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
        <h1 class="title">{{ artDetail.title }}</h1>

        <div class="info">
          <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
          <span>发布时间：{{ formatDate(artDetail.pub_date) }}</span>
          <span>所属分类：{{ artDetail.cate_name }}</span>
          <span>状态：{{ artDetail.state }}</span>
        </div>
        
        <!-- 分割线 -->
        <el-divider></el-divider>

        <img :src="'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img" alt="" />

        <div v-html="artDetail.content"></div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";

import defaultImg from "@/assets/images/cover.jpg";

import dayjs from 'dayjs'
export default {
  components: { quillEditor },
  name: "ArtList",
  data() {
    return {
      detailVisible: false,
      artDetail:{},// 存储文章详情数据
      total:0,
      haha: "file",
      artcleList: [],
      artList: [],   //文章分类数据
      addArtDialog: false,
      artcleForm: {
        title: "",
        cate_id: "",
        content: "",
        cover_img: null,
        state: "已发布",
      },
      rules: {
        title: [
          { required: true, message: "请输入文章的标题", trigger: "blur" },
          { min: 1, max: 30, message: "请输入1~30文章的标题", trigger: "blur" },
        ],
        cate_id: [
          { required: true, message: "请选择文章的分类", trigger: "change" },
        ],
        content: [
          { required: true, message: "请输入文章内容", trigger: "change" },
        ],
      },
      // 查询参数对象

      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: "",
      },
    };
  },
  methods: {
    async showArtDetail(id){
     const {data:res} =await this.$axios.get('/my/article/info',{params:{id}})
      console.log(res);
      this.artDetail = res.data
      this.detailVisible = true
    },
    // 重置功能
    resetAll(){
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: "",
        state: "",
      },
      this.artIcleList()
    },
    //删除数据
    delArt(id){
      this.$confirm('是否确认删除?, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await this.$axios.delete('/my/article/info?id='+id)
          //  console.log(res)
          if (res.code !== 0) return this.$message.error(res.message)
          this.$message.success(res.message)

          if (this.artcleList.length===1){
            this.q.pagenum--
          }
          this.artIcleList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
     
    },
    // 分页器 
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.q.pagenum = 1
        this.q.pagesize = val
        this.artIcleList()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.q.pagenum = val
        this.artIcleList()
      },
    formatDate(time){
    
    return dayjs(time).format('YYYY-MM-DD HH-mm-ss')
      
    },
    // 获取文章数据列表
    async artIcleList() {
      const { data: res } = await this.$axios.get("/my/article/list", {
        params: this.q,
      });
      if (res.code !== 0) return this.$message.error(res.message);
      this.$message.success(res.message);
      this.artcleList = res.data;
      this.total = res.total
    },
    // 清空发布表单
    resetForm() {
      this.$refs.form.resetFields();
      this.artcleForm.cover_img = null;
      this.haha = "text";
      this.$refs.imgRef.setAttribute("src", defaultImg);

      this.artcleForm.state = "已发布";
    },
    // 发布草稿btn按钮
    pubArticle(state) {
      this.artcleForm.state = state;
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        if (this.artcleForm.cover_img === null)
          return this.$message.error("请上传文章封面");
        const fd = new FormData();
        // fd.append('title',this.artcleForm.title)
        // fd.append('cate_id',this.artcleForm.cate_id)
        // fd.append('content',this.artcleForm.content)
        // fd.append('cover_img',this.artcleForm.cover_img)
        // fd.append('state',this.artcleForm.state)
        // fd.forEach((value,key) =>{
        //   console.log('value',value);
        //   console.log('key',key);
      
        Object.keys(this.artcleForm).forEach((key) => {
          fd.append(key, this.artcleForm[key]);
        });
        const { data: res } = await this.$axios.post("/my/article/add", fd);
        if (res.code !== 0) return this.$message.error(res.message);
        this.$message.success(res.message);
        this.addArtDialog = false;
        this.artIcleList()
      });
    },

    async getArtList() {
      const { data: res } = await this.$axios.get("/my/cate/list");

      if (res.code !== 0) return this.$message.error(res.message);
      this.$message.success(res.message);

      this.artList = res.data;
    },
    // change事件 获取file
    uplocdImg(e) {
      const file = e.target.files[0];
      if (file) {
        // console.log(file);
        this.artcleForm.cover_img = file;

        const url = URL.createObjectURL(file);

        // console.log(url);
        // this.$refs.imgRef.src = url
        console.log("选择", file);
        console.log("打开页面", this.$refs.imgRef);
        this.$refs.imgRef.setAttribute("src", url);
      } else {
        // console.log(file);
        this.$refs.imgRef.setAttribute("src", defaultImg);
      }
    },
  },
  created() {
    this.getArtList();
    this.artIcleList();
    this.formatDate()
  },
};
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

/deep/ .ql-container {
  height: 300px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
